#!/usr/bin/python2.7
# -*- coding:UTF-8 -*-

import os
import commands
import shutil
import sys
import tool


# plist文件管理者
PlistBuddy = '/usr/libexec/PlistBuddy'

# 证书管理
security = '/usr/bin/security'

# 签名管理
codesign = '/usr/bin/codesign'

# 工作目录
WDir = '.'


# ipa包重签名
def resign(reSignPath = '', channelName = ''):
    'ipa包重签名'
    global WDir
    if len(reSignPath):
        pass
    else:
        reSignPath = tool.change_symbol(raw_input('输入签名路径(默认使用当前路径):').rstrip(), '-')
        if len(reSignPath) == 0:
            reSignPath = os.path.split(sys.argv[0])[0]

    # 保存工作目录
    old_path = os.getcwd()
    # 改变到签名目录
    os.chdir(reSignPath)
    print '打包目录:' + os.getcwd()

    # 判断需要签名Payload文件夹是否存在
    if os.path.isdir('%s/Payload' % WDir):
        print ' 开始签名 '.center(80, '*')
    else:
        print '***Error*** : 没有需要签名的Payload文件夹'
        return

    # 获取证书描述文件
    print '签名证书描述文件列表:'
    fileList = os.listdir(WDir)
    count = 0
    mobileprovisionFile = ''
    for i in range(0, len(fileList)):
        if fileList[i].endswith('.mobileprovision'):
            count += 1
            mobileprovisionFile = fileList[i]
            print '%d.%s' % (count, fileList[i])

    if count > 1:
        while 1:
            mobileprovisionFile = raw_input('请选择复制给出列表的文件名:')
            if len(mobileprovisionFile) > 0:
                break
    elif count == 0:
        print '***Error*** : 没有找到描述文件'
        return

    # 导出描述文件信息
    fo = open('%s/mobileprovision.plist' % WDir, 'w')
    (status, output) = commands.getstatusoutput('security cms -D -i %s/%s' % (WDir, mobileprovisionFile))
    if status:
        print '执行报错:%s' % output
    else:
        fo.write(output)
    fo.close()

    fo = open('%s/entitlements.plist' % WDir, 'w')
    (status, output) = commands.getstatusoutput('%s -x -c "Print :Entitlements" %s/mobileprovision.plist' % (PlistBuddy, WDir))
    if status:
        print '执行报错:%s' % output
    else:
        fo.write(output)
        # 用完删除
        if os.path.isfile('%s/mobileprovision.plist' % WDir):
            os.remove('%s/mobileprovision.plist' % WDir)
    fo.close()

    # 配置参数
    teamID = ''
    (status, output) = commands.getstatusoutput('%s -c "Print :com.apple.developer.team-identifier" %s/entitlements.plist' % (PlistBuddy, WDir))
    if status:
        print '执行报错:%s' % output
    else:
        teamID = output

    bundleID = ''
    (status, output) = commands.getstatusoutput('%s -c "Print :CFBundleIdentifier" %s/Payload/%s/Info.plist' % (PlistBuddy, WDir, tool.change_symbol(get_appName('%s/Payload' % WDir))))
    if status:
        print '执行报错:%s' % output
    else:
        bundleID = output

    (status, output) = commands.getstatusoutput('%s -c "Set :application-identifier %s.%s" %s/entitlements.plist' % (PlistBuddy, teamID, bundleID, WDir))
    if status:
        print '执行报错:%s' % output

    # 配置 keychain-access-groups
    if len(channelName) == 0:
        channelName = raw_input('输入渠道商:')

    if len(channelName):
        (status, output) = commands.getstatusoutput('%s -c "Print :keychain-access-groups" %s/%s/Info.plist' % (
        PlistBuddy, WDir, tool.change_symbol(channelName)))
        if status:
            # print '执行报错:%s(%s)' % (output, '%s -c "Print :keychain-access-groups" %s/%s/Info.plist' % (PlistBuddy, WDir, tool.change_symbol(channelName)))
            while 1:
                keychain = raw_input('按提示填入keychain-access-groups(提示:渠道SDK要求):')
                if len(keychain):
                    (status, output) = commands.getstatusoutput(
                        '%s -c "Add :keychain-access-groups:0 string %s.%s" %s/entitlements.plist' % (
                            PlistBuddy, teamID, keychain, WDir))
                    if status:
                        print '执行报错:%s' % output
                else:
                    break
        else:
            output = output.replace('Array', '')
            output = output.replace(' ', '')
            output = output.replace('{', '')
            output = output.replace('}', '')
            listArr = output.splitlines()
            i = 0
            while i < len(listArr):
                if len(listArr[i]) > 0:
                    keychain = raw_input('按提示填入keychain-access-groups(提示:%s):' % listArr[i])
                    if len(keychain) > 0:
                        (status, output) = commands.getstatusoutput(
                            '%s -c "Add :keychain-access-groups:0 string %s.%s" %s/entitlements.plist' % (
                            PlistBuddy, teamID, keychain, WDir))
                        if status:
                            print '执行报错:%s' % output
                    else:
                        i -= 1
                i += 1
    else:
        while 1:
            keychain = raw_input('按提示填入keychain-access-groups(提示:渠道SDK要求):')
            if len(keychain):
                (status, output) = commands.getstatusoutput(
                    '%s -c "Add :keychain-access-groups:0 string %s.%s" %s/entitlements.plist' % (
                        PlistBuddy, teamID, keychain, WDir))
                if status:
                    print '执行报错:%s' % output
            else:
                break

    # 根据teamID查找钥匙串
    keySign = ''
    (status, output) = commands.getstatusoutput('security find-identity -v -p codesigning | grep %s' % teamID)
    if status:
        print '执行报错:%s,钥匙串查找失败' % output
        return
    else:
        keySign = output.split('"')[1]
    print '匹配的钥匙串信息:' + keySign

    # 开始签名操作
    # 删除旧的签名文件
    if os.path.exists('%s/Payload/%s/_CodeSignature' % (WDir, get_appName('%s/Payload' % WDir))):
        shutil.rmtree('%s/Payload/%s/_CodeSignature' % (WDir, get_appName('%s/Payload' % WDir)))
    # 复制描述文件到ipa包
    shutil.copyfile(os.path.join(WDir, mobileprovisionFile), '%s/Payload/%s/embedded.mobileprovision' % (WDir, get_appName('%s/Payload' % WDir)))

    # 签名Frameworks库文件
    if os.path.isdir('%s/Payload/%s/Frameworks' % (WDir, get_appName('%s/Payload' % WDir))):
        frameworkList = os.listdir('%s/Payload/%s/Frameworks' % (WDir, get_appName('%s/Payload' % WDir)))
        for i in range(0, len(frameworkList)):
            if frameworkList[i].endswith('.framework'):
                print 'codesign : ' + frameworkList[i]
                (status, output) = commands.getstatusoutput('%s -f -s "%s" %s/Payload/%s/Frameworks/%s/%s' % (codesign, keySign, WDir, tool.change_symbol(get_appName('%s/Payload' % WDir)), frameworkList[i], frameworkList[i].split('.framework')[0]))
                if status:
                    print '执行失败:%s' % output
                else:
                    print output

            elif frameworkList[i].endswith('.dylib'):
                print 'codesign : ' + frameworkList[i]
                (status, output) = commands.getstatusoutput('%s -f -s "%s" %s/Payload/%s/Frameworks/%s' % (codesign, keySign, WDir, tool.change_symbol(get_appName('%s/Payload' % WDir)), frameworkList[i]))
                if status:
                    print '执行失败:%s' % output
                else:
                    print output

    # 签名.app文件
    (status, output) = commands.getstatusoutput('%s -f -s "%s" --entitlements %s/entitlements.plist %s/Payload/%s' % (codesign, keySign, WDir, WDir, tool.change_symbol(get_appName('%s/Payload' % WDir))))
    if status:
        print '执行失败:%s' % output
    else:
        print '签名成功:' + output


    # 获取ipa包信息来命名
    displayName = ''
    (status, output) = commands.getstatusoutput('%s -c "Print :CFBundleDisplayName" %s/Payload/%s/Info.plist' % (PlistBuddy, WDir, tool.change_symbol(get_appName('%s/Payload' % WDir))))
    if status:
        print '执行失败:%s' % output
    else:
        displayName = output

    shortVersion = ''
    (status, output) = commands.getstatusoutput('%s -c "Print :CFBundleShortVersionString" %s/Payload/%s/Info.plist' % (PlistBuddy, WDir, tool.change_symbol(get_appName('%s/Payload' % WDir))))
    if status:
        print '执行失败:%s' % output
    else:
        shortVersion = output

    bundleVersion = ''
    (status, output) = commands.getstatusoutput('%s -c "Print :CFBundleVersion" %s/Payload/%s/Info.plist' % (PlistBuddy, WDir, tool.change_symbol(get_appName('%s/Payload' % WDir))))
    if status:
        print '执行失败:%s' % output
    else:
        bundleVersion = output

    # 判断是否为Dis
    beta = ''
    (status, output) = commands.getstatusoutput('%s -c "Print :beta-reports-active" %s/entitlements.plist' % (PlistBuddy, WDir))
    if status:
        beta = 'Hoc'
    else:
        beta = 'Dis'

    new_ipaName = ''
    if len(channelName):
        new_ipaName = '%s_%s_%s(%s)_%s' % (channelName, displayName, shortVersion, bundleVersion, beta)
    else:
        new_ipaName = '%s_%s(%s)_%s' % (displayName, shortVersion, bundleVersion, beta)
    print '新的ipa名字:' + new_ipaName

    # 压缩只能在当前路径才能打包成功
    tool.zip_file('./Payload', './%s.ipa' % new_ipaName)


    # 恢复到工作目录
    os.chdir(old_path)

    return new_ipaName



# 获取app文件名
def get_appName(PayloadPath):
    '获取app文件路径'
    appNameList = os.listdir(PayloadPath)
    for i in range(0, len(appNameList)):
        if appNameList[i].endswith('.app'):
            appName = appNameList[i]
            return appName


# if __name__ == '__main__':
#     resign()
